import { useUserStore } from "/src/stores/user.js";
import { marked } from "marked";

const BASE_URL = 'http://10.162.4.220:8090/api/chat';

const chatService = {
    sendMessage(content, onMessageCallback, onErrorCallback) {
        const userStore = useUserStore();

        // Request validation
        if (!content?.trim()) {
            onErrorCallback?.(new Error('Message cannot be empty'));
            return { close: () => {} };
        }

        if (!userStore.token) {
            onErrorCallback?.(new Error('User not authenticated'));
            return { close: () => {} };
        }

        const requestData = {
            content: String(content),
            files: [],
            inputs: {},
            userId: userStore.id,
            apiKey: "app-PivZn4marb0vrbO6QrwmWZxs"
            //
        };

        const abortController = new AbortController();
        let isProcessing = true;
        let accumulatedAnswer = '';
        let markdownContent = '';

        console.log('Sending request:', {
            url: BASE_URL + '/stream',
            data: requestData
        });

        const timeoutId = setTimeout(() => {
            abortController.abort();
            const err = new Error('Request timeout (30s)');
            onErrorCallback?.(err);
        }, 30000);

        fetch(`${BASE_URL}/stream`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${userStore.token}`,
                'Accept': 'text/event-stream'
            },
            body: JSON.stringify(requestData),
            credentials: 'include',
            signal: abortController.signal
        })
            .then(async response => {
                clearTimeout(timeoutId);

                if (!response.ok) {
                    const text = await response.text();
                    throw new Error(text || `HTTP error! Status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                try {
                    while (isProcessing) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        buffer += decoder.decode(value, { stream: true });
                        const lines = buffer.split('\n\n');
                        buffer = lines.pop() || '';

                        for (const line of lines) {
                            if (!line.trim()) continue;

                            try {
                                // Parse SSE event data
                                const event = {};
                                line.split('\n').forEach(part => {
                                    const idx = part.indexOf(':');
                                    if (idx > 0) {
                                        const key = part.substring(0, idx).trim();
                                        const value = part.substring(idx + 1).trim();
                                        event[key] = value;
                                    }
                                });

                                if (event.data) {
                                    const data = JSON.parse(event.data);

                                    // Handle message chunks
                                    if (data.event === 'message' && data.answer !== undefined) {
                                        accumulatedAnswer += data.answer;
                                        markdownContent = marked.parse(accumulatedAnswer);
                                        onMessageCallback?.({
                                            type: 'chunk',
                                            content: data.answer,  // Only the new chunk
                                            accumulated: accumulatedAnswer,
                                            html: markdownContent
                                        });
                                    }
                                    // Handle stream end
                                    else if (data.event === 'message_end') {
                                        isProcessing = false;
                                        onMessageCallback?.({
                                            type: 'end',
                                            content: accumulatedAnswer,
                                            html: markdownContent
                                        });
                                        reader.cancel();
                                        return;
                                    }
                                }
                            } catch (parseError) {
                                console.warn('Parse error:', parseError);
                            }
                        }
                    }
                } finally {
                    reader.releaseLock();
                }
            })
            .catch(err => {
                clearTimeout(timeoutId);
                if (err.name !== 'AbortError') {
                    console.error('Request failed:', err);
                    if (err.message.includes('401')) userStore.logout();
                    onErrorCallback?.(err);
                }
            });

        return {
            close: () => {
                isProcessing = false;
                abortController.abort();
                clearTimeout(timeoutId);
            },
            isProcessing: () => isProcessing
        };
    }
};

export default chatService;